package com.qf.juc.demo;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class ArrayListdemo {

    // ConcurrentModificationException 并发修改异常 解决方案
    public static void main(String[] args) {
//        arraylist();
//        vector();
        collections();
//        copyonwrite();
    }

    /**
     * 1、会产生ConcurrentModificationException 并发修改异常
     */
    public static void arraylist(){
        List<String> list = new ArrayList<>();

        for (int i = 1; i < 100; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.err.println("当前线程为："+Thread.currentThread().getName()+":"+"\n"+list);
            },String.valueOf(i)).start();

        }

    }

    /**
     * 2、能够解决并发安全问题，但是效率比较低
     */

    public static void vector(){
        Vector<String> list = new Vector<>();

        for (int i = 1; i < 10; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.err.println("当前线程为："+Thread.currentThread().getName()+":"+"\n"+list);
            },String.valueOf(i)).start();

        }

    }

    /**
     * 3、能够解决并发安全问题，效率比较高
     */

    public static void collections(){
        List<String> list = Collections.synchronizedList(new ArrayList<>());

        for (int i = 1; i < 100; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.err.println("当前线程为："+Thread.currentThread().getName()+":"+"\n"+list);
            },String.valueOf(i)).start();

        }

    }

    /**
     * 4、能够很好的解决并发安全问题，效率高，推荐使用
     */

    public static void copyonwrite(){
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 1; i < 100; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.err.println("当前线程为："+Thread.currentThread().getName()+":"+"\n"+list);
            },String.valueOf(i)).start();

        }

    }

}
